package com.softcits.sb01.filter;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(urlPatterns= {"/*"})
public class RequestAccessStatics implements Filter {
	
	Map<String, Integer> accessStatisticMap = new HashMap<String, Integer>();
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		//获得被访问URL
		String requestedPath = httpRequest.getServletPath();
		
		if(accessStatisticMap.containsKey(requestedPath)) {
			Integer sum = accessStatisticMap.get(requestedPath);
			sum ++;
			accessStatisticMap.put(requestedPath, sum);
		}
		else {
			accessStatisticMap.put(requestedPath, 1);
		}
		
		Set<String> urlSet =  accessStatisticMap.keySet();
		
		for(String urlStr : urlSet) {
			System.out.println("被访问的URL: " + urlStr + "-->" + accessStatisticMap.get(urlStr));
		}
		
		//System.out.println("拦截要访问的请求: " + requestedPath);
		//继续向下传递
		
		System.out.println(new Date());
		chain.doFilter(request, response);
		System.out.println(new Date());
	}

}
